public class BinarySearch {

    public static void main(String[] args) {
        System.out.println(searchInsert1(new int[]{0, 1, 3, 4}, 2));
    }

    public static int searchInsert1(int[] nums, int target) {
        int index = 0;
        int n = nums.length;
        int left = 0;
        int right = n - 1;
        while (left <= right) {
            int mid = left + (right - left + 1) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] == target) {
                return mid;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }

    public int searchInsert2(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        if (nums[left] < target) {
            return n;
        }
        return left;
    }

    public int searchInsert3(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1;
        if (nums[0] > target) {
            return 0;
        }
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                return mid;
            }
        }
        return left;
    }
}
